/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved.
 */

package com.xinyue.server.framework.server.websocket;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.xinyue.server.framework.handlermapping.IGameMessage;
import com.xinyue.server.framework.message.GameMessagePackage;
import com.xinyue.server.framework.server.common.GameMessageCodecService;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.base64.Base64;
import io.netty.handler.codec.base64.Base64Encoder;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Base64Utils;

import java.nio.charset.StandardCharsets;

/**
 * 游戏网络通信编码Handler，负责处理向网络层发送消息之前，将消息序列化为ByteBuf
 *
 * @author 王广帅
 * @since 2021/5/30 19:12
 */
public class WebSocketEncoderHandler extends ChannelOutboundHandlerAdapter {
    private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketEncoderHandler.class);


    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {

        if (msg instanceof GameMessagePackage) {
            GameMessagePackage response = (GameMessagePackage) msg;
            ByteBuf byteBuf = GameMessageCodecService.encode(response,null);
            byte[] array = byteBuf.array();
            String text = Base64Utils.encodeToString(array);
            ctx.channel().writeAndFlush(new TextWebSocketFrame(text));
        } else {
            super.write(ctx, msg, promise);
        }
    }
}
